<template>
  <!-- 系统目录 公共目录 -->
  <div class="MedicenCata">
    <!-- main -->
    <div class="main">
      <!-- left -->
      <div class="main-left">
        <!-- tree -->
        <el-tree
            :data="elTree"
            :props="defaultProps"
            node-key="label"
            :default-expanded-keys="['全部']"
            accordion
            @node-click="handleNodeClick"
            class="custom-tree"
        >
					<span class="custom-tree-node" slot-scope="{ node, data }" style="font-size: 12px;">
						<span :name="node.label">
							<i v-if="!data.children"
                 :class="node.expanded ? 'el-icon-openFile' : 'el-icon-closeFiles'"></i>
							<i v-else class="el-icon-openFile"></i>{{ node.label }}
						</span>
					</span>
        </el-tree>
      </div>
      <!-- right -->
      <div class="main-right" ref="mainRight">
        <!-- tit -->
        <div class="main-icon">
          <div class="main-icon-c">
            <span
                style="font-size: 12px;color: #606266;font-weight: bold;display: inline-block;width: 68px;">关键字：</span>
            <el-input size="mini" placeholder="输入名称搜索"
                      v-model="searchValue" clearable @keyup.enter.native="handClick(0)"></el-input>
          </div>
          <!-- btn3 -->
          <div class="main-icon-c">
            <el-button v-for="(v,i) in headerBtn" :key="i" :type="v.type" :loading="loading" :icon="v.icon" size="mini"
                       @click="handClick(i)">{{ v.title }}
            </el-button>
          </div>
        </div>
        <!-- add data -->
        <!-- messagesBox -->
        <!-- table -->
        <div class="table">
          <el-table :data="tableData" border height="70vh" style="width: 100%" @row-click="handleShowRow">
            <template v-for="col in tableRows">
              <el-table-column
                  :key="col.prop"
                  :prop="col.prop"
                  :label="col.name"

                  :width="col.width || undefined"
              >
                <!-- 仅对 type/state 特殊处理，其他字段原样显示 -->
                <template #default="{ row }">
                  <template v-if="col.prop === 'type'">
                    {{ typeMap[row.type] || row.type }} <!-- 类型转换 -->
                  </template>
                  <template v-else-if="col.prop === 'state'">
                    <el-tag :type="row.state === 1 ? 'success' : 'danger'">
                      {{ stateMap[row.state] || row.state }} <!-- 状态转换 + 标签样式 -->
                    </el-tag>
                  </template>
                  <template v-else>
                    {{ row[col.prop] }} <!-- 其他字段直接显示 -->
                  </template>
                </template>
              </el-table-column>
            </template>
            <!-- fixed -->
            <el-table-column fixed="left" label="行号" type="index" align="center"></el-table-column>
            <!-- edit -->
            <el-table-column fixed="right" label="操作" width="200px">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" :disabled="scope.row.clinicId === 0"
                           v-if="permissionsArr.includes('system:docrute:edit')" @click="handleClickEdit(scope.row)">
                  编辑
                </el-button>
                <el-button type="primary" @click="handleClick(scope.row)" size="mini">
                  项目对照
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>


      </div>
    </div>
    <!-- feet -->
    <div class="feet">
      <!-- messagesBox -->
      <div class="messagesBox">
        <el-dialog
            :title="watch"
            :visible.sync="dialogVisible"
            width="40%"
            :before-close="handleClose">
          <!-- messagesBox / tabs -->
          <div class="tabs">
            <el-form :model="contrastItemForm" :inline="true" size="mini" :disabled="true">

              <el-form-item label="" prop="code">
                <span style="width: 68px;margin-right: 2px;font-weight: bold;">名称:</span>
                <el-input v-model="contrastItemForm.name"></el-input>
              </el-form-item>

              <el-form-item label="" prop="status">
                <span style="width: 68px;margin-left: 2px;font-weight: bold;">其他名称:</span>
                <el-input v-model="contrastItemForm.otherName"></el-input>
              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 50px;margin-left: 2px;font-weight: bold;">类型:</span>
                <el-select v-model="contrastItemForm.type">
                  <el-option label="注射" :value="1"/>
                  <el-option label="输液" :value="2"/>
                  <el-option label="口服" :value="3"/>
                  <el-option label="外用" :value="4"/>
                  <el-option label="输血" :value="5"/>
                  <el-option label="其他" :value="6"/>
                </el-select>
              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 68px;margin-left: 2px;font-weight: bold;">适用对象:</span>
                <el-select v-model="contrastItemForm.lmtSpc">
                  <el-option
                      v-for="item in applyTargetOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>


            <div class="table-header">
              <el-button-group class="transparent-btn-group">
                <el-button type="" icon="el-icon-plus" size="mini" class="transparent-btn"
                           @click="handleAdd" v-if="permissionsArr.includes('system:cosrute:add')"></el-button>
                <el-button type="" icon="el-icon-edit" size="mini" class="transparent-btn" :disabled="!selectedRow"
                           @click="handleEdit" v-if="permissionsArr.includes('system:cosrute:edit')"></el-button>
                <el-button type="" icon="el-icon-circle-close" size="mini" class="transparent-btn" :disabled="!selectedRow"
                           @click="handleDelete" v-if="permissionsArr.includes('system:cosrute:remove')"></el-button>
              </el-button-group>
            </div>


            <div class="table">
              <el-table :data="tableData2" border
                        @row-click="handleRowClick"
                        highlight-current-row
                        :style="{ width: windowWidth + 'px' }"
                        ref="myTable">
                <template v-for="col in tableRows2">
                  <el-table-column
                      :key="col.prop"
                      :prop="col.prop"
                      :label="col.name"
                      align="center"
                      :formatter="(row) => formatColumn(row, col.prop)"
                  >
                  </el-table-column>
                </template>
                <!-- fixed -->
                <el-table-column fixed="left" label="行号" type="index"></el-table-column>
              </el-table>
            </div>
          </div>
        </el-dialog>


        <div class="tabs">
          <el-dialog
              title="新增"
              :visible.sync="addDialogVisible"
              width="35%"
              :before-close="handleClose">
            <el-form :model="cosruteAddForm" :inline="true" size="mini">

              <el-form-item label="" prop="code">
                <span style="width: 35px;margin-right: 2px;font-weight: bold;">类别:</span>
                <el-select v-model="cosruteAddForm.type" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in typeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="" prop="status">
                <span style="width: 68px;margin-left: 2px;font-weight: bold;">适用对象:</span>
                <el-select v-model="cosruteAddForm.ruteLmtSpc" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in applyTargetOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>

              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 35px;margin-left: 2px;font-weight: bold;">项目:</span>
                <el-select v-model="cosruteAddForm.costId" style="width: 300px" size="mini"
                           popper-class="compact-select" @focus="loadOptions" filterable>
                  <el-option
                      v-for="item in projectOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 60px;margin-left: 2px;font-weight: bold;">计次方式:</span>
                <el-select v-model="cosruteAddForm.cntType" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in countTypeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 60px;margin-left: 2px;font-weight: bold;">收费方式:</span>
                <el-select v-model="cosruteAddForm.costType" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in costTypeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell" v-if="cosruteAddForm.costType === 4">
                <span style="width: 60px;margin-left: 2px;font-weight: bold;">收费次数:</span>
                <el-input type='number' v-model="cosruteAddForm.costCnt"
                          @input="handleChargeNumberCorrect"
                          popper-class="compact-select" style="width: 150px">
                </el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="handleAddData" size="mini">确 定</el-button>
    </span>
          </el-dialog>
        </div>

        <div class="tabs">
          <el-dialog
              title="修改"
              :visible.sync="editDialogVisible"
              width="35%"
              :before-close="handleClose">
            <el-form :model="cosruteEditForm" :inline="true" size="mini">

              <el-form-item label="" prop="code">
                <span style="width: 35px;margin-right: 2px;font-weight: bold;">类别:</span>
                <el-select v-model="cosruteEditForm.type" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in typeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="" prop="status">
                <span style="width: 68px;margin-left: 2px;font-weight: bold;">适用对象:</span>
                <el-select v-model="cosruteEditForm.ruteLmtSpc" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in applyTargetOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>

              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 35px;margin-left: 2px;font-weight: bold;">项目:</span>
                <el-select v-model="cosruteEditForm.costId" style="width: 300px" size="mini"
                           popper-class="compact-select">
                  <el-option
                      v-for="item in projectOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 60px;margin-left: 2px;font-weight: bold;">计次方式:</span>
                <el-select v-model="cosruteEditForm.cntType" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in countTypeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="twoLine" label="" prop="textSpell">
                <span style="width: 60px;margin-left: 2px;font-weight: bold;">收费方式:</span>
                <el-select v-model="cosruteEditForm.costType" popper-class="compact-select" style="width: 150px">
                  <el-option
                      v-for="item in costTypeOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="handleEditData" size="mini">确 定</el-button>
    </span>
          </el-dialog>
        </div>
      </div>

      <el-dialog
          :close-on-click-modal="false"
          :title="cosruteTitel"
          :visible.sync="addCosruteDialogVisible"
          width="50%"
          @close="handleCloseAddCosrute"
          class="responsive-dialog"
      >
        <el-form
            ref="cosruteFormRef"
            :model="cosruteForm"
            :rules="cosruteFormRules"
            label-position="right"
            size="mini"
            class="responsive-form"
        >
          <!-- 第一行 -->
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="编码" prop="code">
                <el-input v-model="cosruteForm.code" placeholder="自动生成" disabled/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="名称" prop="name">
                <el-input v-model="cosruteForm.name" @input="handleConvertingPinyin" placeholder="请输入名称"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否执行" prop="exeB">
                <el-select v-model="cosruteForm.exeB" placeholder="请选择" style="width:100%">
                  <el-option label="否" :value="0"/>
                  <el-option label="是" :value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="状态">
                <el-select v-model="cosruteForm.state" placeholder="请选择" style="width:100%">
                  <el-option label="禁用" :value="0"/>
                  <el-option label="启用" :value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行 -->
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="给药方式类型" prop="type">
                <el-select v-model="cosruteForm.type" placeholder="请选择" style="width:100%" @change="handleSelCode">
                  <el-option label="注射" :value="1"/>
                  <el-option label="输液" :value="2"/>
                  <el-option label="口服" :value="3"/>
                  <el-option label="外用" :value="4"/>
                  <el-option label="输血" :value="5"/>
                  <el-option label="其他" :value="6"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="适用对象">
                <el-select v-model="cosruteForm.lmtSpc" placeholder="请选择" style="width:100%">
                  <el-option
                      v-for="item in applyTargetOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="修改数量">
                <el-input-number
                    v-model="cosruteForm.modifyCnt"
                    :min="0"
                    controls-position="right"
                    style="width:100%"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="显示顺序">
                <el-input-number
                    v-model="cosruteForm.orderId"
                    :min="0"
                    controls-position="right"
                    style="width:100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第三行 -->
          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="其他名称">
                <el-input v-model="cosruteForm.otherName" placeholder="请输入其他名称"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
              <el-form-item label="拼音简码">
                <el-input v-model="cosruteForm.pyCode" placeholder="输入名称自动生成" disabled/>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 备注单独一行 -->
          <el-form-item label="备注">
            <el-input
                v-model="cosruteForm.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="addCosruteDialogVisible = false">取消</el-button>
          <el-button size="mini" type="primary" @click="addCosruteForm">确定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>/

<script>

import {
  addCosrute,
  addCosruteForm,
  deleteCosrute,
  editCosruteForm,
  getChargingPrice,
  getCosrute,
  getMedicationFrequency,
  updateCosrute
} from "@/api/cosrute/Cosrute";
import {pinyin} from "pinyin-pro";
import {withLoading} from "@/untils/loading";
import {dict} from "@/api/staff/staff";

export default {
  components: {},
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      selectedRow: null,
      watch: '查看',
      searchValue: '',
      toCodeNum: '0000',//拼接自增 导零
      iconHandleClick: 'el-icon-plus',
      CatalogueName: '',
      DropDownedName: '可用',
      typeValue: '',
      YNuseVaule: '可用',
      nowDateTimeValue: '',
      windowWidth: '', // 实时宽度
      iconComes: 'el-icon-dangan',
      operatingTime: '',
      // boolean
      disabled: true,
      noEidt: true,
      formdisabled: true,
      loading: false,
      dialogVisible: false,	//此乃查看/编辑控制
      addDialogVisible: false, //此乃新增控制
      addCosruteDialogVisible: false, //此乃新增控制
      cosruteTitel: '', //标题
      editDialogVisible: false, //此乃新增控制
      // number
      dataIndex: 0,
      CodeNumber: 0,
      pageNum: 1, //当前页currentPage
      pageSize: 8,
      totalSize: 10, //总条数
      typeSelect: null,
      /* obj */
      // 新增
      cosruteForm: {
        code: '',        // 编码
        exeB: 1,         // 是否执行
        name: '',        // 名称
        type: null,      // 给药方式类型
        lmtSpc: 0,       // 适用对象
        modifyCnt: 0,    // 修改数量
        orderId: 0,      // 显示顺序
        otherName: '',   // 其他名称
        pyCode: '',      // 拼音简码
        remark: '',      // 备注
        state: 1         // 状态
      },
      cosruteFormRules: {
        exeB: [{required: true, message: '请选择是否执行', trigger: 'change'}],
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 1, max: 100, message: '长度在1到100个字符', trigger: 'blur'}
        ],
        type: [{required: true, message: '请选择给药类型', trigger: 'change'}]
      },

      cosruteEditForm: {
        costId: null,
        ruteId: null,
        cntType: 0,
        costCnt: null,
        costType: 1,
        dosUnt: '',
        dpurcId: null,
        drugGrpsum: null,
        drugId: null,
        feeType: null,
        frquId: null,
        id: null,
        lmtDrug: null,
        costName: '',
        type: 1,
        ruteLmtSpc: 0,
      },
      isLookData: false,
      cosruteAddForm: {
        costId: null,
        ruteId: null,
        cntType: 0,
        costCnt: null,
        costType: 1,
        dosUnt: '',
        dpurcId: null,
        drugGrpsum: null,
        drugId: null,
        feeType: null,
        frquId: null,
        id: null,
        lmtDrug: null,
        costName: '',
        type: 1,
        ruteLmtSpc: 0,
      },
      // 编辑 / 查看
      contrastItemForm: {
        id: null,
        name: '',
        otherName: '',
        type: '',
        lmtSpc: '',
      },
      // arr
      data: [],
      oop: [],
      userInfo: [],
      watchData: [],
      // title右侧按钮
      headerBtn: [
        {search: "search", title: "搜索", type: "success"},
        {add: "add", title: "新增", type: "warning",auth:'system:docrute:add'},
      ],

      projectOptions: [],
      rxTypeOptions: [],
      typeOptions: [{id: 1, label: '项目'}, {id: 2, label: '材料'}],
      applyTargetOptions: [{id: 0, label: '全部'}, {id: 1, label: '西药'}, {id: 2, label: '中药'}, {id: 3, label: '卫材'}],
      countTypeOptions: [{id: 0, label: '频率计次'}, {id: 1, label: '数量计次'}],
      costTypeOptions: [{id: 1, label: '不限'}, {id: 2, label: '首次'}, {id: 3, label: '续次1'},
        {id: 4, label: '固定次数'}, {id: 5, label: '医嘱首次'}, {id: 6, label: '次日起计费'}],
      cosruteTypeOptions: [{id: 1, label: '注射'}, {id: 2, label: '输液'}, {id: 3, label: '口服'},
        {id: 4, label: '外用'}, {id: 5, label: '输血'}, {id: 6, label: '其他'}],


      typeMap: {
        1: '注射',
        2: '输液',
        3: '口服',
        4: '外用',
        5: '输血',
        6: '其他',
      },

      // 状态映射表
      stateMap: {
        0: '禁用',
        1: '可用',
      },
      // title右侧按钮
      tableRows: [
        {name: "系统序号", prop: "id", type: "", width: 70}, {
          name: "编码",
          prop: "code",
          nz: "nz",
          width: 50
        }, {name: "名称", prop: "name", type: ""},
        {name: "其他名称", prop: "otherName", type: ""}, {name: "类型", prop: "type", type: ""}, {
          name: "有效状态",
          prop: "state",
          type: ""
        },
        {name: "操作时间", prop: "createTime", type: ""}, {name: "备注", prop: "remark", type: ""}
      ],

      tableRows2: [
        {name: "项目名称", prop: "costName", type: "", width: 70}, {name: "项目序号", prop: "costId", width: 50},
        {name: "适用对象", prop: "ruteLmtSpc", type: ""}, {name: "类别", prop: "type", type: ""}, {
          name: "收费方式",
          prop: "costType",
          type: ""
        },
        {name: "收费次数", prop: "costCnt", type: ""}, {name: "计次方式", prop: "cntType", type: ""},
        {name: "用药频率", prop: "frquId", type: ""}
      ],

      elTree: [
        {
          label: '全部',
          path: '',
          title: '',
          icon: 'el-icon-news',
          children: [
            {label: '注射', id: '1'},
            {label: '输液', id: '2'},
            {label: '口服', id: '3'},
            {label: '外用', id: '4'},
            {label: '输血', id: '5'},
            {label: '其他', id: '6'},
          ]
        }
      ],
      tableData: [],
      tableData2: [],
      permissionsArr:[],
    };
  },
  computed: {
    // 格式化数字，确保4个0后的数字自增时不会出现前导零
    formattedNumber() {
      return '00000' + this.toCodeNum.toString().slice(1);
    },
  },
  mounted() {
    this.loadData();
    this.loadOptions();
    this.permissionsArr = JSON.parse(localStorage.getItem('permissions'))
     this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    // this.addForm.operator = this.userInfo.userName
    //获取动态盒子宽度，实时赋值给右侧 => this.$refs.mainRight.offsetWidth;
    this.$nextTick(() => {
      this.updateWindowWidth();
      window.addEventListener('resize', this.updateWindowWidth);
    })
    this.nowDateTime();
  },
  methods: {
    handleShowRow(row) {
      console.log(row, 'rowrowrow')

    },
    handleClickEdit(row) {
      this.cosruteTitel = "编辑给药方式";
      this.cosruteForm = JSON.parse(JSON.stringify(row));
      this.addCosruteDialogVisible = true;
    },

    async handleSelCode() {
      let res = await getMedicationFrequency();
      this.cosruteForm.code = res.data[res.data.length - 1].id + 1;
    },
    handleConvertingPinyin() {
      this.cosruteForm.pyCode = pinyin(this.cosruteForm.name, {
        pattern: 'first',
        toneType: 'none',
        separator: ''
      }).toLocaleUpperCase();
    },

    handleCloseAddCosrute() {
      this.cosruteForm = Object.assign({}, this.$options.data.call(this).cosruteForm);
      this.addCosruteDialogVisible = false;
    },

    async addCosruteForm() {
      const valid = await this.$refs.cosruteFormRef.validate();
      if (!valid) {
        return;
      }
      await withLoading(this, '数据提交中...')(async () => {
        if (this.cosruteForm.id == null) {
          const res = await addCosruteForm(this.cosruteForm);
          if (res.code === 200) {
            await this.loadData();
            this.addCosruteDialogVisible = false;
          } else {
            this.$message.error(res.message)
          }
        } else {
          const res1 = await editCosruteForm(this.cosruteForm);
          if (res1.code === 200) {
            await this.loadData();
            this.addCosruteDialogVisible = false;
          } else {
            this.$message.error(res1.message)
          }
        }
      });

    },
    handleChargeNumberCorrect() {
      this.cosruteAddForm.costCnt = this.cosruteAddForm.costCnt <= 0 ? null : this.cosruteAddForm.costCnt;
    },

    handleRowClick(row) {
      //高亮
      this.$refs.myTable.setCurrentRow(row);
      const table = this.$el.querySelector('.el-table__body');
      table.querySelectorAll('tr').forEach(tr => {
        tr.classList.remove('perm-highlight');
      });
      event.currentTarget.classList.add('perm-highlight');
      this.selectedRow = row;
    },

    async handleEdit() {
      this.editDialogVisible = true;
      this.cosruteEditForm = {...this.selectedRow}
    },


    formatColumn(row, prop) {
      const value = row[prop];
      switch (prop) {
        case 'type':
          return this.mapToLabel(value, this.typeOptions);

        case 'cntType':
          return this.mapToLabel(value, this.countTypeOptions);

        case 'costType':
          return this.mapToLabel(value, this.costTypeOptions);

        case 'ruteLmtSpc':
          return this.mapToLabel(value, this.applyTargetOptions);

        default:
          return value; // 默认原样显示
      }
    },

    // 通用数字转文字方法
    mapToLabel(value, options) {
      if (value === undefined || value === null) return '';
      const found = options.find(item => item.id == value);
      return found ? found.label : value;
    },


    async handleAddData() {
      if (!this.cosruteAddForm.costId) {
        this.$message.warning('请选择项目')
        return
      }
      await withLoading(this, '数据提交中...')(async () => {
        this.cosruteAddForm.ruteId = this.contrastItemForm.id
        const newItem = {
          ...this.cosruteAddForm,
          costName: (() => {
            const projectName = this.projectOptions.find(item => item.id === this.cosruteAddForm.costId)
            return projectName ? projectName.name : `未知项目(ID: ${this.cosruteAddForm.costId})`
          })()
        }

        let res = await addCosrute([newItem]);
        if (res.code === 200) {
          this.addDialogVisible = false
        } else {
          this.$message.error(res.message)
        }
        this.cosruteAddForm = Object.assign({}, this.$options.data.call(this).cosruteAddForm)
        this.tableData2.push(newItem)
      });
    },

    async handleEditData() {
      if (!this.cosruteEditForm.costId) {
        this.$message.warning('请选择项目')
        return
      }
      await withLoading(this, '数据提交中...')(async () => {

        this.cosruteEditForm.ruteId = this.contrastItemForm.id
        const newItem = {
          ...this.cosruteEditForm,
          costName: (() => {
            const projectName = this.projectOptions.find(item => item.id === this.cosruteEditForm.costId)
            return projectName ? projectName.name : `未知项目(ID: ${this.cosruteEditForm.costId})`
          })()
        }
        const res = await updateCosrute([newItem]);
        if (res.code === 200) {
          const index = this.tableData2.findIndex(
              item => item.id === this.cosruteEditForm.id
          );
          this.$set(this.tableData2, index, {...newItem});
          this.editDialogVisible = false
        } else {
          this.$message.error(res.message)
        }
      });
      // 4. 关闭对话框
    },


    async loadOptions() {
      let res = await getChargingPrice();
      this.projectOptions = res.data.map(item => ({
        id: item.id,    // 根据实际接口字段调整
        name: item.costname // 根据实际接口字段调整
      }));
    },

    handleAdd() {
      this.cosruteAddForm = Object.assign({}, this.$options.data.call(this).cosruteAddForm)
      this.addDialogVisible = true; // 打开第二个对话框
    },

    async loadData() {
      let res = await getMedicationFrequency({
        type: this.typeSelect == null ? null : this.typeSelect,
        name: this.searchValue === '' ? '' : this.searchValue
      });
      if (res.code === 200) {
        this.tableData = res.data;
        this.totalSize = res.data.totalSize;
        this.pageSize = res.data.pageSize
      } else {
        this.$message.error(res.message);
      }
    },
    /*
      about tree
    */
    handleNodeClick(data) {
      this.typeSelect = data.id;
      this.loadData();
    },

    /*
      about table
    */
    aa() {
      this.loadData(); // loadData 测试更新数据驱动
    },
    // // 数据源
    // async getditc(){
    //    let res = await dict()
    //    console.log(res.data);
    // },
    // col 里面包含了表头字段和名称，list 是表格数据
    columnWidth(col, list) {
      let prop = col.prop, lab = col.lab;
      let width = 40; // 设定一个最小值
      let maxlenStr = ""; // 最长字符串
      for (let info of list) {
        if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
      }
      width = Math.max(width, len(lab), len(maxlenStr));
      // 表格自带的内边距(20px) 自调
      return width + 12; // 这里加了 12px
      function len(str) {
        // 实际分配长度可根据需要自行调整
        let length = 18;
        for (const char of str + "") {
          // 英文小写字符 8px
          if ("a" <= char && char <= "z") length += 8;
          // 英文大写字符 8px
          else if ("A" <= char && char <= "Z") length += 8;
          // 中文字符 28px
          else if (char >= "\u4e00" && char <= "\u9fa5") length += 18;
          // 其他 8px
          else length += 8;
        }
        return length;
      }
    },


    handleDelete() {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        if (this.selectedRow === null){
          this.$message.warning("请选中数据再进行操作")
        }
        await withLoading(this, '删除中...')(async () => {
          let res = await deleteCosrute({id: this.selectedRow.id});
          if (res.code === 200) {
            this.tableData2 = this.tableData2.filter(item => item.id !== this.selectedRow.id);
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => {

      });
    },
    // edit table
    async handleClick(val) {
      let res = await getCosrute({id: val.id});
      this.tableData2 = res.data
      console.log(res, 'resres')
      this.contrastItemForm = JSON.parse(JSON.stringify(val))
      this.watch = '项目对照';
      this.dialogVisible = true;
      this.noEidt = true;
      this.formdisabled = false;
    },

    inputLabel() {
      this.addForm.code = this.makePy(this.addForm.label).toLocaleUpperCase().slice(0, 1) + this.formattedNumber + this.CodeNumber;//编码
      this.addForm.textSpell = this.makePy(this.addForm.label).toLocaleUpperCase();
    },
    handleClose(done) {
      this.tableData2 = [];
      this.cosruteAddForm = Object.assign({}, this.$options.data.call(this).cosruteAddForm)
      this.formdisabled = false;
      this.dialogVisible = false
    },
    // db events

    // 步骤
    handClick(i) {
      // i event
      switch (i) {
        case 0:
          this.loadData();
          break;
        case 1:
          this.cosruteTitel = "新增给药方式";
          this.addCosruteDialogVisible = true;
          break;
      }
    },
    handleCommand(command) {
      // console.log(command);
      // 根据 command 值执行相应的逻辑
      switch (command) {
        case 'a':
          // 处理a的逻辑
          console.log('执行A逻辑');
          this.DropDownedName = '可用'
          break;
        case 'b':
          // 处理b的逻辑
          console.log('执行B逻辑');
          this.DropDownedName = '禁用'
          break;
        case 'c':
          // 处理b的逻辑
          break;
          // ... 其他 case
      }
    },
    //分页
    //每页条数改变触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.pageNum = 1;
      this.loadData();
    },
    //当前条数改变触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.loadData();
    },
    // 实时宽度
    updateWindowWidth() {
      this.windowWidth = window.innerWidth - 288;
    },
    // 系统当前日期时间
    nowDateTime() {
      const now = new Date(); //创建时间日期对象
      const year = now.getFullYear(); //年
      const month = now.getMonth() + 1; //月份是从0开始的
      const day = now.getDate(); //日
      const hours = now.getHours(); //小时
      const minutes = now.getMinutes(); //分钟
      const seconds = now.getSeconds(); //秒
      const currentDate = `${year}-${month}-${day}`.replace(/-/g, '') //替换操作
      this.nowDateTimeValue = `${year}-${month}-${day}` + ` ` + `${hours}:${minutes}:${seconds}`
      // this.datetimesinglend =
      // 将字符串转换为Date对象
      // console.log(this.nowDateTimeValue);
    }
  }
}
</script>
<style lang="less" scoped>
.el-table :deep(.perm-highlight) {
  background-color: #000 !important;
}

.el-table :deep(.perm-highlight) > td {
  background-color: transparent !important;
}

/* 覆盖Element默认高亮色 */
.el-table :deep(.current-row) {
  background-color: #000 !important;
}


.el-select-dropdown__item {
  padding: 6px 10px;
  font-size: 12px;
  line-height: 20px;
}

.el-select-dropdown__empty {
  padding: 8px 0; /* 空状态间距 */
  font-size: 12px;
}

.transparent-btn-group {
  background-color: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.transparent-btn {
  background-color: transparent !important;
  border: none !important;
  color: white !important; /* 图标设为白色 */
  padding: 6px 8px !important;
  font-size: 14px !important;
}

.transparent-btn:hover {
  background-color: rgba(255, 255, 255, 0.2) !important; /* 悬停效果 */
}

.transparent-btn:active {
  transform: scale(0.95);
}

.table-container {
  width: 100%; /* 跟随弹窗宽度 */
  padding: 0;
  margin: 0;
}

.table-header {
  background-color: #39648f; /* 深蓝色，与图片一致 */
  color: white;
  padding: 3px 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 5px 4px 0 0;

}

.header-title {
  font-size: 16px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.table {
  margin-top: 0;
  width: 100%;
}

.footer-actions {
  margin-top: 15px;
  text-align: right;
}


// 穿透
/deep/ .el-input.is-disabled .el-input__inner {
  color: #87898f;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  color: #87898f;
}

/deep/ .el-icon-arrow-left:before {
  content: "\e67d";
  font-size: 18px;
}

/deep/ .el-dialog__title {
  font-size: 12px;
  color: #fff;
}

/deep/ .el-dialog__headerbtn {
  top: 12px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

/deep/ .el-dialog__headerbtn .el-dialog__close:hover {
  color: #00007f;
}

/deep/ .el-dialog__header {
  background-color: #39648f;
  padding: 8px;
}

/deep/ .el-dialog__body {
  padding: 0 20px 0 20px;
  border: 1px solid #efefef;
  padding: 8px;
}

/deep/ .el-dropdown-menu__item {
  font-size: 12px;
}

/deep/ .el-descriptions {
  font-size: 12px !important;
}

/deep/ .el-descriptions-item__container {
  display: flex !important;
  // align-items: center !important;
  padding-top: 12px !important;
}

/deep/ .el-descriptions-item__label:not(.is-bordered-label) {
  padding-left: 0;
  width: 66px;
  display: flex;
  justify-content: right;
}

/deep/ .el-color-picker__icon, .el-input, .el-textarea {
  width: 100%;
}

// content
.MedicenCata {
  height: 100%;
  width: 100%;
  // header
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #efefef;
    padding: 4px;

    // justify-content: space-evenly;
    // icon
    .header-icon {
      display: flex;
      align-items: center;
    }

  }

  // main
  .main {
    width: 100%;
    margin-left: 8px;
    display: flex;
    justify-content: left;
    overflow-y: auto; /* 当内容超出容器高度时显示垂直滚动条 */
    // left
    .main-left {
      .custom-tree {
        max-height: 100%; /* 设置树形菜单的最大高度为父容器的100% */
        overflow-y: auto; /* 当内容超出设定高度时显示滚动条 */
      }

      /deep/ .el-tree-node__content {
        height: 40px;
        padding-left: 0 !important;
      }

      /deep/ .el-tree-node__label {
        font-size: 12px;
      }

      width: 10%;
      height: 100%;
    }

    // right
    .main-right {
      width: 85%;
      height: 100%;
      // alert
      .addmessagesBox {
        .tabs {
          padding: 12px;
          border: 1px solid #f8f8f8;
          background-color: #fefefe;

          /deep/ .el-select > .el-input {
            width: 172px;
          }

          /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner {
            width: 172px;
          }

          /deep/ .el-form-item__content {
            display: flex;

            span {
              font-size: 12px;
            }
          }

          .oneLine {
            width: 524px;
            // background-color: indianred;
          }
        }

        /deep/ .el-dialog__title {
          font-size: 12px;
          font-weight: bold;
        }

        /deep/ .el-table {
          font-size: 12px;
        }
      }

      // icon
      .main-icon {
        display: flex;
        align-items: center;
        padding: 12px;
        line-height: 40px;

        .main-icon-a {
          // width: 240px;
          // background-color: #00557f;
        }

        .main-icon-b {
          margin-left: 28px;

          /deep/ .el-dropdown {
            font-size: 12px;
            cursor: pointer;
          }

          /deep/ .el-dropdown:hover {
            font-weight: bold;
            color: #66b1ff;
          }

          /deep/ .el-icon--right {
            // background-color: #66b1ff;
          }

          /deep/ .el-popper[x-placement^=bottom] {
            margin-top: 0;
          }
        }

        // c
        .main-icon-c {
          display: flex;
          margin-left: 28px;

          /deep/ [data-v-2bacc09b] .el-color-picker__icon, .el-input[data-v-2bacc09b], .el-textarea[data-v-2bacc09b] {
            width: 80%;
          }
        }
      }

      // table
      /deep/ .el-table .cell {
        font-size: 12px;
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div :first-child {
        text-align: center;
      }

      /deep/ .el-table td.el-table__cell div {
        text-align: center;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }

      .table {
        padding: 12px;
      }
    }
  }

  // feet
  .feet {

    // alert
    .messagesBox {
      .tabs {

        /deep/ .el-form-item__content {
          display: flex;

          span {
            font-size: 12px;
          }
        }

        .oneLine {
          width: 524px;
          // background-color: indianred;
        }

        .oneLineBox {
          display: flex;
          // 循环子按钮
        }
      }

      /deep/ .el-dialog__title {
        font-size: 12px;
      }

      /deep/ .el-table {
        font-size: 12px;
      }
    }
  }

}
</style>